import {
  addFoodCart,
  deleteFoodCart,
  updateFoodCart,
  queryFoodCart,
  queryFoodCartForCart
} from '../../utils/ReturnAxios';
  import {Toast} from '../../utils/toast';
  import saveLocal from '@/utils/NoLogSaveCart';
  import axios from 'axios';
  
  export default {
    namespaced: true,
    state: {
      cartIcon: null,
      userinfo: null,
      login: true,

      cartanimateArray: [], // 购物车动画数组
      cartanimateNumber: 0, // 购物车变化数量
      aftrerDiscountMoney: 0, // 优惠后总金额
      discountMoney: 0, // 优惠金额
      totalWorkingFee: 0,
      obj: {},
      canAfterSaleCount: 0, // 可售后数量
      isLoadShowCart: false, //是否在登录后才可以加入购物车
      selectLadderList: [], //阶梯加价增
      selectGiftList: [], // 阶梯赠品
      buyMoreData: [], // 每满加价增
      orderConfig: {type: 'isPutTimeSort', order: ''},
      allMoreBuy: null, //当前所有可参加 每满加
      allLadderList: null, // 当前所有可参加的阶梯加赠
      allGiftList: [], // 当前所有 可参加 阶梯送礼活动
      cartAddNum: 1, // 添加动画
      cartFoodArray: null,
      activeCartList: null,
      checkedCartList: [], //已选商品项目
      foodAcitveData: [], //在线活动列表
      foodSelectData: [], //离线线选中列表
      activeCartList:[],
      itemQuery:[], //商品评论数据
      activeInfor:null,  //商品促销活动信息
    },
    getters: {  
      selectGiftList: state => {
        var selectGiftList = state.selectGiftList;
        var allGiftList = state.allGiftList;
        var returnSelectGiftList = selectGiftList.filter((list, index) => {
          return allGiftList.some(item => {
            var isSome = item.goodsCode == list.goodsCode && item.promId == list.promId;
            if (isSome) {
              selectGiftList[index].goodsCodeList = item.goodsCodeList
              list.promCode = item.promCode;
            }
            return isSome;
          });
        });
        return returnSelectGiftList;
      },
      buyMoreData: state => {
        var obj = state.allMoreBuy;
        var selectLadderList = state.buyMoreData;
        var resSelectLadderList = [];
        if (!obj) {
          return resSelectLadderList;
        }
        selectLadderList.map(item => {
          var resgoodsList = obj[item.promId];
          if (resgoodsList) {
            item.goodsList = resgoodsList.goodsList;
            item.promCode = resgoodsList.promCode;
            resSelectLadderList.push(item);
          }
        });
        return resSelectLadderList;
      },
      selectLadderList: state => {
        var obj = state.allLadderList;
        var selectLadderList = state.selectLadderList;
  
        var resSelectLadderList = [];
  
        selectLadderList.map(item => {
          var resgoodsList = obj[item.promId];
          if (resgoodsList) {
            item.goodsList = resgoodsList.goodsList;
            item.promCode = resgoodsList.promCode;
            resSelectLadderList.push(item);
          }
        });
        return resSelectLadderList;
      },
      buyMorePrice: (state, getters) => {
        var price = 0;
        var buyMoreData = getters.buyMoreData;
        var allLadderList = getters.selectLadderList;
        if (buyMoreData.length > 0 || allLadderList.length > 0) {
          allLadderList.map(item => {
            var addMoney = item.addMoney || 0;
            price += addMoney;
          });
          buyMoreData.map(item => {
            var addMoney = item.addMoney || 0;
            var selectNum = item.selectNum || 0;
            price += addMoney * selectNum;
          });
        }
        return price;
      },
      totalPrice(state) {
        var allPrice = 0;
        state.checkedCartList.map(item => {
          var commodityPrice = item.addPrice || 0;
          var workingInfo = item.workingInfo ? JSON.parse(item.workingInfo) : {procemoney: 0};
          var procePriceoney = workingInfo.procemoney || 0;
          allPrice += (parseFloat(commodityPrice) + parseFloat(procePriceoney)) * (item.goodsNum || 0);
        });
        return allPrice;
      },
  
      discountMoney(state) {
        var discountMoney = state.discountMoney;
        return discountMoney;
      },
  
      totalWorkingFee(state) {
        var totalWorkingFee = state.totalWorkingFee;
        return totalWorkingFee;
      },
      cartList(state) {
        return state.activeCartList || [];
      },
      foodAcitveData(state) {
        return state.foodAcitveData || [];
      },
  
      foodSelectData(state) {
        return state.foodSelectData || [];
      },
       //商品数量
      cartNum(state) {
        var count = 0;
        var activeCartList = state.activeCartList;
        if (state.activeCartList) {
          // var list = state.activeCartList
          // list.map((item) => {
          //   count += item.goodsNum
          // })
          count = activeCartList.length;
          return count;
        }
        return 0;
      },

      cartTotalNum(state) {
        var count = 0;
        var activeCartList = state.activeCartList;
        if (state.activeCartList) {
          var list = state.activeCartList;
          list.map(item => {
            var goodsNum = item.goodsType == 7 ? 1 : item.goodsNum || 0;
            count += goodsNum;
          });
          return count;
        }
        return 0;
      },
      // 订单商品评论数据
      itemQuery(state) {
        return state.itemQuery || [];
      },
      // 订单凑单活动
      activeInfor(state) {
        return state.activeInfor || {};
      },
    },
  
    actions: {
      changeCheckedCartListly({commit}, data){//保存一个值用来表示购物车里面勾选的数据
    		commit('CHANGE_CHECKED_CART_LISTLY', data);
    	},
      async clearFoodDetail({commit, state}) {
        commit('CLEAR_FOOD_DETAIL');
      },
       //合并购物车
      async synFoodCart({dispatch, commit}) {
        var cartFoodArray = localStorage.getItem('cartFoodArray');
        var sessionId = localStorage.getItem('sessionId')
        if (!cartFoodArray || !sessionId) {
          dispatch('queryCart');
          return;
        }
        cartFoodArray = cartFoodArray ? JSON.parse(cartFoodArray) : [];
        var cartList = [];
        for (var list of cartFoodArray) {
          var shoppingCartLists = list.shoppingCartLists;
          var addCartList = shoppingCartLists.map(item => {
            return {
              goodsId: item.goodsId,
              goodsCode: item.goodsCode,
              goodsType: item.goodsType,
              storeCode: item.storeCode,
              goodsNum: item.goodsNum,
              serve: item.serve,
              workingInfo: item.workingInfo,
              goodsDeliveryType: item.goodsDeliveryType,
              addPrice: item.addPrice,
              goodsWeight:item.goodsWeight,
              processingList:item.processingList
            };
          });
          cartList = cartList.concat(addCartList);
        }
        if (cartList.length > 0) {
          var res = await addFoodCart(cartList);
          res = res.data;
          if (res.returnCode == 0) {
            Toast({
              message: res.msg,
              type: 'fail',
            });
            return;
          }
        }

        //准备清本地空购物车吧
        localStorage.setItem('cartFoodArray', '');
        commit('QUERY_CART', res.data);
      },
      //获得购物车数量
      async queryCart({commit, dispatch, state}) {
        commit('CLEAR_CART');
        var sessionId = localStorage.getItem('sessionId');
        sessionId = sessionId == 'undefined' ? '' : sessionId;
        if (!sessionId && !state.isLoadShowCart) {
          dispatch('queryCartFromLocal');
          return;
        }
        var res = await queryFoodCart();
        res = res.data;
        commit('QUERY_CART', res.data);
      },

      async clearFoodDetail({commit, state}) {
        commit('CLEAR_FOOD_DETAIL');
      },
      // 从本地获取购物车相关信息
      queryCartFromLocal({commit}) {
        var cartFoodArray = localStorage.getItem('cartFoodArray');
        cartFoodArray = cartFoodArray ? JSON.parse(cartFoodArray) : [];
        commit('QUERY_CART', cartFoodArray);
      },

      // 添加到购物车
      async addShoppingCart({commit}, config) {
        var res = await addFoodCart(config);
        res = res.data;
        if (res.returnCode == 0) {
          Toast({
            message: res.msg,
            type: 'fail',
          });
          return;
        }

        commit('QUERY_CART', res.data);
      },

      //更新购物车数量
      async updataCart({commit}, config) {

        var res = await updateFoodCart(config);
        res = res.data;
        if (res.returncode == 0 || res.returnCode == 0) {
          Toast({
            message: res.msg,
            type: 'fail',
          });
        }
        commit('UPDATA_CART', res);

      },
      // 从购物车中删除setStoreConfig
      async deleCart({commit}, config) {
        var ids = [];
        config.shoppingCartList.map(item => {
          ids.push(item.rid);
        });
        ids = ids.join(',');
        var res = await deleteFoodCart(ids);
        res = res.data;

        if (res.returncode == 0 || res.returnCode == 0) {
          Toast({
            message: res.msg,
            type: 'fail',
          });
        }
        var shoppingCartList = config.shoppingCartList;
        commit('DELE_CART', shoppingCartList);

      },
      //购物车动画
      addCartAnimate({commit}, num) {
        commit('ADD_CART_ANIMATE', num);
      },
    },
    mutations: {   
      // 促销商品活动信息
      SET_ACTIVEINFOR(state,data){
        state.activeInfor = data
      },
      // 订单商品评论数据
      SET_ITEMQUERY(state,data) {
        console.log(data,'data')
        state.itemQuery = data;
      },

      CHANGE_CHECKED_CART_LISTLY(state, data){//保存一个值用来表示购物车里面勾选的数据
        state.checkedCartList = data;
        // console.log(state.shopLacks,"保存在vuex里面的shopLacks值")
      },   
      //获取购物车的数据
      QUERY_CART(state, data) {
        state.cartFoodArray = data;
        var storeCode = localStorage.getItem('storeCode');
        var activeCart = state.cartFoodArray.find(item => {
          return storeCode == parseInt(item.storeCode);
        });
        if (activeCart) {
          state.activeCartList = activeCart.shoppingCartLists;
        } else {
          state.activeCartList = [];
        }
      },
      //清除购物相关数据
      CLEAR_CART(state, data) {
        state.cartFoodArray = null;
      },
      QUERY_ACTIVE_LIST(state) {
        var storeCode = localStorage.getItem('storeCode');
        var cartFoodArray = state.cartFoodArray || []
        var activeCart = cartFoodArray.find(item => {
          return storeCode == parseInt(item.storeCode);
        });
        if (activeCart) {
          state.activeCartList = activeCart.shoppingCartLists;
        } else {
          state.activeCartList = [];
        }
      },

      // 购物车列表中 更新数据
      UPDATA_CART(state, data) {
        data.data.map(newData => {
          var goodsId = newData.goodsId;
          var isInCheckedCartLis;
          var oldDataIndex = state.activeCartList.findIndex(item => {
            return item.goodsId == goodsId;
          });
          if (oldDataIndex !== -1) {
            var oldData = state.activeCartList[oldDataIndex];
            oldData.goodsNum = newData.goodsNum || oldData.goodsNum;
            oldData.serve = newData.serve;
            oldData.preorder = newData.preorder;
            state.activeCartList.splice(oldDataIndex, 1, oldData);
          } else {
            state.activeCartList.push(newData);
          }

          if (/\/cart$/gi.test(window.location.hash)) {
            return;
          }
          isInCheckedCartLis = state.checkedCartList.find(item => {
            return item.goodsId == goodsId;
          });
          if (!isInCheckedCartLis) {
            state.checkedCartList.push(newData);
          }
        });
      },
      //
      ADD_CART_FROM_LOCAL(state, data) {
        var activeCartList = state.activeCartList || [];

        for (var list of data) {
          var goodsId = list.goodsId;

          var oledDataIndex = activeCartList.findIndex(item => {
            return item.goodsId == goodsId;
          });
          if (oledDataIndex == -1) {
            activeCartList.push(list);
          } else {
            var number = activeCartList[oledDataIndex].goodsNum;
            list.goodsNum = list.goodsNum + number;
            activeCartList.splice(oledDataIndex, 1, list);
          }
        }

        state.activeCartList = activeCartList;

        saveLocal(activeCartList,'cartFoodArray');
      },

      // 从本地 购物车列表中更新数据
      UPDATA_CART_FROM_LOCAL(state, data) {
        var activeCartList = state.activeCartList || [];

        for (var list of data) {
          var goodsId = list.goodsId;

          var oledDataIndex = activeCartList.findIndex(item => {
            return item.goodsId == goodsId;
          });
          if (oledDataIndex == -1) {
            activeCartList.push(list);
          } else {
            activeCartList.splice(oledDataIndex, 1, list);
          }
        }

        state.activeCartList = activeCartList;

        saveLocal(activeCartList,'cartFoodArray');
      },

      CHANGE_ALL_CHECKED(state, data) {
        state.activeCartList.map((item, index) => {
          item.preorder = data;
          state.activeCartList.splice(index, 1, item);
        });
      },

      CHANGE_CHECKED(state, data) {
        var goodsId = data.goodsId;
        var findIndex = state.activeCartList.findIndex(item => {
          return item.goodsId == goodsId;
        });
        if (findIndex != -1) {
          var item = state.activeCartList[findIndex];
          item.preorder = data.isChecked;
          state.activeCartList.splice(findIndex, 1, item);
        }
      },

      // 从购物车列表中删除
      DELE_CART(state, data) {
        var cartList = state.activeCartList;
        data.map(item => {
          for (var i = 0; cartList.length; i++) {
            if (cartList[i].rid == item.rid) {
              cartList.splice(i, 1);
              break;
            }
          }
        });
        state.activeCartList = cartList;
      },

      DELE_CART_FROM_LOCAL(state, data) {
        var cartList = state.activeCartList;
        data.map(item => {
          for (var i = 0; cartList.length; i++) {
            if (cartList[i].goodsId == item.goodsId) {
              cartList.splice(i, 1);
              break;
            }
          }
        });
        saveLocal(cartList,'cartFoodArray');
      },

      CHANGE_CHECKED_CART_LIST(state, data) {
        state.checkedCartList = data;
      },
      //添加购物车动画
      ADD_CART_ANIMATE(state, num = 1) {
        state.cartAddNum = num;
        state.cartanimateArray.push(state.cartanimateNumber++);
        setTimeout(() => {
          state.cartanimateArray.shift();
        }, 600);
      },
      SET_CART_ICON(state, data) {
        state.cartIcon = data;
      },
      CHANGE_DISCOUNT_MONEY(state, data) {
        state.discountMoney = data || 0;
      },
      CLEAR_OFF_LINE_DETAIL(state) {
        state.buyMorePrice = 0;
        state.aftrerDiscountMoney = 0;
        state.totalWorkingFee = 0;
        state.discountMoney = 0;
      },
      // 改变已优惠价格 和 优惠后的价格
      INIT_PRICE(state, data) {
        state.aftrerDiscountMoney = data.aftrerDiscountMoney;
        state.discountMoney = data.discountMoney;
        state.totalWorkingFee = data.totalWorkingFee;
      },
      //堂食点餐专用
      SET_FOOD_ACTIVE_DATA(state, data) {
        data.sort(function (a, b) {
          return a.rid < b.rid;
        });
  
        state.foodAcitveData = data;
      },
  
      SET_FOOD_SELECT_DATA(state, data) {
        state.foodSelectData = data;
      },
  
      FOOD_CHANGE_ALL_CHECKED(state, data) {
        state.foodAcitveData.map((item, index) => {
          item.preorder = data;
          state.foodAcitveData.splice(index, 1, item);
        });
      },
      CLEAR_FOOD_DETAIL(state) {
        state.buyMorePrice = 0;
        state.aftrerDiscountMoney = 0;
        state.totalWorkingFee = 0;
        state.discountMoney = 0;
      },
      // 改变已优惠价格 和 优惠后的价格
    INIT_PRICE(state, data) {
      state.aftrerDiscountMoney = data.aftrerDiscountMoney;
      state.discountMoney = data.discountMoney;
      state.totalWorkingFee = data.totalWorkingFee;
    },

    // 改变已选择的满赠 阶梯加赠
    CHANGE_SELECT_BUY_MORE_LIST: (state, data) => {
      var selectGiftList = state.selectGiftList;
      var promId = data.promId;
      var goodsCode = data.goodsCode
      var selecIndex = selectGiftList.findIndex(item => {
        return promId == item.promId && goodsCode == item.goodsCode
      });
      if (selecIndex != -1) {
        selectGiftList.splice(selecIndex, 1, data);
      } else {
        selectGiftList.push(data);
      }
      state.selectGiftList = selectGiftList;
    },

    //替换已选择的满赠 赠品列表
    SPLICE_SELECT_BUY_MORE_LIST: (state, data) => {
      var selectGiftList = state.selectGiftList;
      var promId = data.promId;
      var goodsCode = data.goodsCode;
      var selecIndex = selectGiftList.findIndex(item => {
        return promId == item.promId && item.goodsCode == goodsCode
      });
      console.log('selecIndex', selecIndex, goodsCode, promId)
      if (selecIndex != -1) {
        selectGiftList.splice(selecIndex, 1);
      }
      state.selectGiftList = selectGiftList;
    },

    // 改变已选择的返利 赠品
    CHANGE_SELECT_LADDER_LIST: (state, data) => {
      var selectLadderList = state.selectLadderList;
      var promId = data.promId;
      var goodsCode = data.goodsCode;
      var selecIndex = selectLadderList.findIndex(item => {
        return promId == item.promId && item.goodsCode == goodsCode;
      });
      if (selecIndex != -1) {
        selectLadderList.splice(selecIndex, 1, data);
      } else {
        selectLadderList.push(data);
      }
      state.selectLadderList = selectLadderList;
    },

    //替换已选择的返利加赠列表
    SPLICE_SELECT_LADDER_LIST: (state, data) => {
      var selectLadderList = state.selectLadderList;
      var promId = data;

      var selecIndex = selectLadderList.findIndex(item => {
        return promId == item.promId;
      });
      if (selecIndex != -1) {
        selectLadderList.splice(selecIndex, 1);
      }
      state.selectLadderList = selectLadderList;
    },

    CHANGE_BUY_MORE_LIST(state, data) {
      var buyMoreData = state.buyMoreData;
      var promId = data.promId;
      var selecIndex = buyMoreData.findIndex(item => {
        return promId == item.promId;
      });
      if (selecIndex != -1) {
        // buyMoreData[selecIndex].selectNum = data.selectNum
        buyMoreData.splice(selecIndex, 1, data);
      } else {
        buyMoreData.push(data);
      }
      state.buyMoreData = buyMoreData;
    },
      INIT_PRODVO_LIST(state, data) {
        var eachEnougts = [];
        var multisteps = [];
        var allLadderList;
        var allMoreBuy;
        var obj = {};
        var objBuyMore = {};
        var arrayGift = [];
        for (var list of data) {
          if (!list.selected) {continue}
          var goodsCode = list.goodsCode;
          var promotionalVoList = list.promotionalVoList || [];
          var promotionalVoListOK = promotionalVoList.filter(item => {
            return item.beUsed == 2;
          });
  
          {
            var leaderList = promotionalVoListOK.filter(item => {
              return item.saleType == 'rebate';
            });
  
            var tt = leaderList.map(item => {
              var promId = item.promId;
              var promCode = item.promCode;
              if (!obj[promId]) {
                obj[promId] = {
                  goodsList: [goodsCode],
                  promCode,
                };
              } else {
                obj[promId].goodsList.push(goodsCode);
              }
            });
          }
  
          {
            var giftList = promotionalVoListOK.filter(item => {
              return item.saleType == 'rebate' && (item.prefWay == 2 || item.prefWay == 1);
            });
  
            giftList.map(item => {
              var promId = item.promId;
              var promCode = item.promCode;
              if (!objBuyMore[promId]) {
                objBuyMore[promId] = {
                  goodsList: [goodsCode],
                  promCode,
                };
              } else {
                objBuyMore[promId].goodsList.push(goodsCode);
              }
            });
          }
  
          {
            promotionalVoListOK.map(item => {
  
              if (item.saleType == 'buyPresent' && item.prefWay == 3) {
  
                if (item.prefRange == 1) {
                  arrayGift.push({
                    goodsCode: goodsCode,
                    goodsCodeList: '',
                    promId: item.promId,
                    promCode: item.promCode,
                    promotLadderVOList: item.promotLadderVOList,
                  });
                } else {
                  var returnIndex = arrayGift.findIndex((val) => {
                    return val.promId == item.promId
                  })
                  if (returnIndex == -1) {
                    arrayGift.push({
                      goodsCode: '',
                      goodsCodeList: [goodsCode],
                      promId: item.promId,
                      promCode: item.promCode,
                      promotLadderVOList: item.promotLadderVOList,
                    });
                  } else {
                    arrayGift[returnIndex].goodsCodeList.push(goodsCode)
                  }
                }
              }
            });
          }
        }
        state.allMoreBuy = objBuyMore;
        state.allLadderList = obj;
        state.allGiftList = arrayGift;
      },

      changeCheckedCartList(state, data) {
        state.checkedCartList = data;
        state.selectLadderList = [] //阶梯加价增
        state.selectGiftList = [] // 阶梯赠品
        state.statebuyMoreData = []
      },
    },
  };
  